import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import CityListView from '../views/CityListView.vue'
import ProfileView from '../views/ProfileView.vue'
import LoginView from '../views/LoginView.vue'
import api from '../services/api'

const routes = [
  { 
    path: '/', 
    component: HomeView,
    meta: { requiresAuth: true }
  },
  { 
    path: '/cities', 
    component: CityListView,
    meta: { requiresAuth: true }
  },
  { 
    path: '/profile', 
    component: ProfileView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    component: LoginView,
    meta: { requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth) {
    if (!token) {
      // 如果没有token，重定向到登录页
      next('/login')
      return
    }
    
    try {
      // 验证token有效性
      await api.get('/auth/verify')
      next()
    } catch (error) {
      console.error('Token verification failed:', error)
      localStorage.removeItem('token')
      next('/login')
    }
  } else {
    // 如果用户已登录且访问登录页，重定向到首页
    if (to.path === '/login' && token) {
      next('/')
      return
    }
    next()
  }
})

export default router